﻿using System;
using System.Data.SqlServerCe;
using System.IO;
using System.Linq;
using System.Reflection;
using gbL.NetBoard.Examples.DoubleMVC.View.Data.Requests;
using gbL.NetBoard.Helpers;

namespace gbL.NetBoard.Examples.DoubleMVC.View.Data
{
    class ProductsTableView : MultiTypedMessageListener
    {
        public ProductsTableView(Blackboard domain) : base(domain) { }

        protected override void OnMessageAdded(object message)
        {
            if (message is ProductRowRequest) Process((ProductRowRequest)message);
        }

        protected override void OnMessageRemoved(object message)
        {
            //
        }

        protected override Type[] MessageTypes
        {
            get { return new[] { typeof(ProductRowRequest) }; }
        }

        void Process(ProductRowRequest message)
        {
            var taken = Messages.Take(x => x.Message == message);
            if (taken.Count == 0) return;

            message.Results = new System.Data.DataTable();

            string SQL = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "gbL.NetBoard.Examples.DoubleMVC.View.Data.Queries.ProductList.query"
            )).ReadToEnd();
            if (message.ProductIDs != null && message.ProductIDs.Length > 0)
            {
                SQL += " WHERE p.[Product ID] IN (" + 
                    string.Join(",", message.ProductIDs.Select(x => x.ToString()).ToArray()) + 
                    ")";
            }
            SQL += " ORDER BY p.[Product ID]";

            using (SqlCeConnection cnn = new SqlCeConnection(Properties.Settings.Default.NorthwindConnectionString))
            {
                cnn.Open();
                SqlCeCommand cmd = new SqlCeCommand(SQL, cnn);
                SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
                da.Fill(0, 999999, message.Results);
                cnn.Close();
            }
        }
    }
}
